package chapter1.bagqueuestack.exercise;

import chapter1.bagqueuestack.example.Stack;
import edu.princeton.cs.algs4.StdIn;

/**
 * 练习1.3.4
 * 从标准输入中读取一个文本流并使用栈判定括号匹配是否完整
 *
 * @author quanlinlin on 2018/12/2 11:57.
 * @version 1.0
 */
public class Parentheses {

    private static final char LEFT_BRACE    = '{';
    private static final char RIGHT_BRACE   = '}';
    private static final char LEFT_BRACKET  = '[';
    private static final char RIGHT_BRACKET = ']';
    private static final char LEFT_PARENTH  = '(';
    private static final char RIGHT_PARENTH = ')';

    public static void main(String[] args) {
        Stack<Character> stringStack = new Stack<>();

        String readString = StdIn.readString();
        for (int i = 0; i < readString.length(); i++) {
            char s = readString.charAt(i);
            if (LEFT_BRACE == s || LEFT_BRACKET == s || LEFT_PARENTH == s) {
                stringStack.push(s);
            } else {
                char pop = stringStack.pop();
                if (pop == LEFT_BRACE && s == (RIGHT_BRACE)) {
                    continue;
                } else if (pop == LEFT_BRACKET && s == (RIGHT_BRACKET)) {
                    continue;
                } else if (pop == LEFT_PARENTH && s == (RIGHT_PARENTH)) {
                    continue;
                } else {
                    stringStack.push(pop);
                    stringStack.push(s);
                }
            }
        }
        if (stringStack.size() == 0) {
            System.out.println("true");
        } else {
            System.out.println("false, and stack size is " + stringStack.size());
        }
    }
}
